#!/bin/sh
# findinstalled
# Wednesday, 03/31/2021
# script to find files installed by specific packages on a Slackware-based distro
# ...grepping around in /var/lib/pkgtools/packages :)
# script by Paul Sherman <psherman2001@gmail.com>
# c2005-2021, GPL3

LFILE=$HOME/FIND_INSTALLED_OUTPUT.TXT
rm -f $LFILE 2>/dev/null
DIALOG=Xdialog
if [[ -d $1 ]]; then
	$DIALOG --rc-file /usr/share/pixmaps/colorboxDOH.rc  --icon /usr/share/pixmaps/doh.xpm  --title "That\'s a directory" \
	--msgbox "\nThis script finds the package that installed a FILE.\n\nNot for use on directories.\n" 0 0
	exit 0
fi

if [ -z "$1" ]; then
	ENTRYDAT=$(zenity --entry --title="Check what package installed a file" --class=findinstalled \
	--text="`printf "...Enter the filename below:"`" \
	--window-icon=/usr/share/pixmaps/findinstalled.xpm --width=400 --entry-text "" 2>/dev/null)
	if [ ! "$ENTRYDAT" ]; then
        exit 0
	fi
else
	ENTRYDAT="$1"
fi

if [ ! -f "$ENTRYDAT" ]; then
    IFS=$'\n'
    foo=( $(grep -R "$ENTRYDAT" /var/lib/pkgtools/packages | cut -d':' -f2 ))
    unset IFS
    if [ -z "$foo" ]; then
        	$DIALOG --rc-file /usr/share/pixmaps/colorboxDOH.rc  --timeout 4 --icon /usr/share/pixmaps/doh.xpm  --title "No results found" \
                        --msgbox "\n Cannot find a file installed\n that includes $ENTRYDAT \n" 0 0
        	exit 0
    fi
    OP=$(zenity --list --text="One of these files?"  --hide-header  --width=620 --height=500 --radiolist --column "Select" --column "File" FALSE ${foo[@]::1} $(printf 'FALSE %s\n' ${foo[@]:1}))
    if [ -z "$OP" ]; then
        exit 0
    fi
    if [ ! -f "/$OP" ]; then
        $DIALOG --rc-file /usr/share/pixmaps/colorboxDOH.rc --timeout 4  --icon /usr/share/pixmaps/doh.xpm  --title "Not Found" \
                    --msgbox "\n That file is no longer installed \n on the computer system. \n" 0 0
        exit 0
    fi
    # looks like we got something after all, so set ENTRYDAT
    ENTRYDAT="/$OP"
fi

# test if this is a symolic link, get link target if so...
ISLINK=`file "$ENTRYDAT" | cut -d\  -f2`
if [ "$ISLINK" == "symbolic" ] ; then
	xx=`readlink -f "$ENTRYDAT"`
	input="$xx"
else
	input="$ENTRYDAT"
fi

echo $input 

yad --info --on-top --width=640 --height=140 --fixed --title="Searching" --text-align center --skip-taskbar --undecorated  --center --no-buttons --text="<span><b><big>\n\nSearching installed programs that contain:\n\n \"$input\"</big></b></span>" &
sleep 1

input_escaped=$(echo $input | sed "s/\./\\\./g")
cd /var/lib/pkgtools/packages
retpath="${input:1}"

grep -R "$retpath$" . | cut -c 3- | cut -d:  -f1 > $LFILE
numlines=`wc -l <$LFILE`

sleep 2

if [ $numlines -lt 1 ]; then
	echo "Done searching packages." > $LFILE
	echo "" >> $LFILE
	echo "No results found." >> $LFILE
	echo "It appears that" >> $LFILE
	echo "\"$1\"" >> $LFILE
	echo "was not directly installed by a package." >> $LFILE
fi
kill $(ps aux | grep 'yad' | awk '{print $2}') 2>/dev/null
scite $LFILE&
exit 0
